package com.dmai.aiet.epc.archive.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmai.aiet.epc.archive.base.LearningCategoryEnum;
import com.dmai.aiet.epc.archive.base.PageResult;
import com.dmai.aiet.epc.archive.entity.SpecialTopicStudyRecords;
import com.dmai.aiet.epc.archive.mapper.SpecialTopicStudyRecordsDao;
import com.dmai.aiet.epc.archive.pojo.vo.LearningAggregateVo;
import com.dmai.aiet.epc.archive.pojo.vo.LearningCertificateItem;
import com.dmai.aiet.epc.archive.pojo.vo.LearningStatItem;
import com.dmai.aiet.epc.archive.service.SpecialTopicStudyRecordsService;
import com.dmai.aiet.epc.archive.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import org.apache.commons.collections4.MapUtils;


@Service
public class SpecialTopicStudyRecordsServiceImpl implements SpecialTopicStudyRecordsService {

    @Autowired
    private SpecialTopicStudyRecordsDao specialTopicStudyRecordsDao;


    /**
     * 查询记录
     *
     * @param id
     * @return
     */
    public SpecialTopicStudyRecords findById(String id) {
        return specialTopicStudyRecordsDao.findById(id);
    }

    @Override
    public LearningAggregateVo getAggregate(String userid) {
        List<SpecialTopicStudyRecords> records = specialTopicStudyRecordsDao.findByUserid(userid, null, null);

        LearningAggregateVo vo = new LearningAggregateVo();
        vo.setCourseCount(records.size());


        vo.setLearningHours(BigDecimal.valueOf(records.stream()
                .map(SpecialTopicStudyRecords::getLearningHours)
                .filter(Objects::nonNull) // 过滤掉为 null 的值
                .reduce((a, b) -> a + b).orElse(0.0)).setScale(2, BigDecimal.ROUND_HALF_UP));

        vo.setCreditHours(BigDecimal.valueOf(records.stream()
                .map(SpecialTopicStudyRecords::getCreditHours)
                .filter(Objects::nonNull) // 过滤掉为 null 的值
                .reduce((a, b) -> a + b).orElse(0.0)).setScale(2, BigDecimal.ROUND_HALF_UP));

        return vo;
    }

    @Override
    public List<LearningStatItem> getStat(String userid, Integer axle, Long startStamp, Long endStamp) {
        List<SpecialTopicStudyRecords> records = specialTopicStudyRecordsDao.findByUserid(userid, new Date(startStamp), new Date(endStamp));

        String format = axle.equals(2) ? "yyyy-MM" : "yyyy-MM-dd";
        Map<String, List<SpecialTopicStudyRecords>> collect = records.stream().map(t -> {
            t.setAxle(DateUtil.format(t.getInitialStudyTime(), format));
            return t;
        }).collect(Collectors.groupingBy(SpecialTopicStudyRecords::getAxle));

        List<LearningStatItem> result = new ArrayList<>();
        LearningStatItem item;
        for (Map.Entry<String, List<SpecialTopicStudyRecords>> entry : collect.entrySet()) {
            item = new LearningStatItem();
            item.setX(entry.getKey());
            item.setLearningHours(BigDecimal.valueOf(entry.getValue().stream().map(SpecialTopicStudyRecords::getLearningHours)
                    .filter(Objects::nonNull)
                    .reduce((a, b) -> a + b).orElse(0.0)).setScale(2, BigDecimal.ROUND_HALF_UP));

            result.add(item);
        }

        List<String> twoDaysX;
        if (axle.equals(2)) {
            twoDaysX = DateUtils.getTwoDaysMonth(startStamp, endStamp);
        } else {
            twoDaysX = DateUtils.getTwoDaysDay(startStamp, endStamp);
        }
        for (String day : twoDaysX) {
            if (!result.stream().map(LearningStatItem::getX).filter(t -> t.equals(day)).findFirst().isPresent()) {
                item = new LearningStatItem();
                item.setX(day);
                item.setLearningHours(BigDecimal.ZERO);
                result.add(item);
            }
        }

        return result.stream().sorted(Comparator.comparing(LearningStatItem::getX).reversed()).collect(Collectors.toList());
    }

    @Override
    public List<LearningCertificateItem> getCertificate(String userid) {
        List<SpecialTopicStudyRecords> list = specialTopicStudyRecordsDao.findCertificateByUserid(userid);

        return list.stream().map(t -> {
            LearningCertificateItem item = new LearningCertificateItem();
            item.setCode(t.getCertificateCode());
            item.setName(t.getCertificateName());
            item.setUrl(t.getCertificateUrl());
            item.setAcquireDate(DateUtil.format(t.getCertificateIssueTime(), "yyyy年MM月dd日"));
            item.setValidity(t.getCertificateValidity());
            item.setCategory(LearningCategoryEnum.specialTopic.getCode());
            return item;
        }).collect(Collectors.toList());
    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    public PageResult<SpecialTopicStudyRecords> pageAll(Map<String, Object> params) {

        Page<SpecialTopicStudyRecords> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
        List<SpecialTopicStudyRecords> list = specialTopicStudyRecordsDao.pageAll(page, params);
        long total = page.getTotal();
        if (total > 0) {

        }
        return PageResult.<SpecialTopicStudyRecords>builder().data(list).code(0).count(total).build();

    }

    /**
     * 列表
     *
     * @param params
     * @return
     */
    public List<SpecialTopicStudyRecords> findAll(Map<String, Object> params) {
        return specialTopicStudyRecordsDao.findAll(params);
    }

}
